using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.SqlClient;
using System.Net.NetworkInformation;
using System.Net;
using System.IO;
using WhoIs;


public partial class _Default : System.Web.UI.Page 
{
    string strResponse = string.Empty;
    string strTrace = string.Empty;
    DataSet dsSchema = new DataSet("Whois");   

  
    protected void Button3_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable("WhoisTable");
        dt.Columns.Add(new DataColumn("DomainName",typeof(string)));
        dt.Columns.Add(new DataColumn("Email", typeof(string)));
        dt.Columns.Add(new DataColumn("ServerType", typeof(string)));
        dt.Columns.Add(new DataColumn("WhoisDetails", typeof(string)));
        dsSchema.Tables.Add(dt);
        DataSet ds = new DataSet();

        string DomainName = string.Empty;
        string Email = string.Empty;
        string ServerType = string.Empty;
        string WhoIsdetails = string.Empty;

        ds.ReadXml(Server.MapPath("patterns.xml"));
        WhoisLookup wl = new WhoisLookup();
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            Regex re = new Regex(dr[0].ToString());
            MatchCollection mc = re.Matches(txtDomaiList.Text.Replace("www.","").ToLower());
            foreach (Match m in mc)
            {
                //Response.Write(m.Value+" " + dr[1].ToString());
                //Response.Write("<BR>");
               // txtResult.Text += wl.Connect(m.Value + Environment.NewLine, dr[1].ToString().Trim());
                //txtResult.Text += "**********************************************************************************" + "\n";
                 DomainName = m.Value;                 
                 WhoIsdetails = wl.Connect(m.Value + Environment.NewLine, dr[1].ToString().Trim());
                 //txtResult.Text += "**********************************************************************************" + "\n";
                 Email = ParseEmail(WhoIsdetails);                 
                 DataRow drSchema = dt.NewRow();
                 drSchema["DomainName"] = m.Value;
                 drSchema["ServerType"] = WhoIs.ProcessRequest.GetServerType("http://www." + DomainName);
                 drSchema["Email"] = Email;
                 drSchema["WhoisDetails"] = WhoIsdetails;
                 dt.Rows.Add(drSchema);                 
            }
        }

        HttpContext.Current.Session["Records"] = dsSchema;

        BindData();

    }

    private void BindData()
    {

        GridView1.DataSource = (DataSet)HttpContext.Current.Session["Records"];
        GridView1.DataBind();
    }

    private string ParseEmail(string whoisDetails)
    {
        string str = string.Empty;
        Regex re = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        MatchCollection mc = re.Matches(whoisDetails);
        foreach (Match m in mc)
        {
            str += m.Value;
            str += "\n";
        }
        return str;
    }
   
    protected void Page_Load(object sender, EventArgs e)
    {

        HttpContext context = HttpContext.Current;
        if (context.Request.Browser.Crawler)
        {
            Session.Abandon();
            return;
        }
       // txtResult.Text = "";
        lblIPaddress.Text = "<center>Your Ip address: " + Request.UserHostAddress + "</center>";
    }
    protected void btnPing_Click(object sender, EventArgs e)
    {
        string[] arrDomainNames = txtDomaiList.Text.Split("\r\n".ToCharArray());
        foreach (string strDomain in arrDomainNames)
        {
            if (strDomain != string.Empty || strDomain != "")
            {
                strResponse += "\r\r";
                strResponse += strDomain + "\r";
                ProcessPingRequest(strDomain);
            }
        }
        WriteFile();
    }

    private void ProcessPingRequest(string strDomain)
    {
        for (int i = 0; i < 4; i++)
        {
            try
            {
                //lblPingTracert.Text = "";
                Ping ping = new Ping();
                PingReply pingreply = ping.Send(strDomain);
                strResponse += "\r";
                strResponse += " Reply from " + pingreply.Address;
                strResponse += " Bytes=" + pingreply.Buffer.Length.ToString();
                strResponse += " time=" + pingreply.RoundtripTime;
                strResponse += " TTL= " + pingreply.Options.Ttl;
            }
            catch (Exception err)
            {
                lblPingTracert.Text += err.Message;
            }
        }
    }
    private void WriteFile()
    {
        string fileName = "Ping" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "") + ".txt";
        FileStream fs = new FileStream(Server.MapPath(fileName), FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write(strResponse);
        sw.Close();
        fs.Close();
        lblPingTracert.Text += "<a href='" + fileName + "' target='_blank'>Click to See response " + DateTime.Now.TimeOfDay + "</a><BR>";
    }
    
    protected void btnTracert_Click(object sender, EventArgs e)
    {
        string[] arrDomainNames = txtDomaiList.Text.Split("\r\n".ToCharArray());
        foreach (string destination in arrDomainNames)
        {
            if (destination != string.Empty || destination != "")
            {
                strTrace += "\r\r";
                strTrace += destination + "\r";
                ProcessTraceRequest(destination);
            }
        }
        WriteTracertFile();
    }

    private void ProcessTraceRequest(string destination)
    {
        try
        {
            string temp = string.Format("Tracing route to {0}", destination);
            strTrace += temp;

            IPAddress ip = Dns.GetHostEntry(destination).AddressList[0];

            Ping pinger = new Ping();

            for (int ttl = 1; ttl != 0; ttl = ttl + 1)
            {
                byte[] b = new byte[32];
                //PingReply r = pinger.Send( 
                PingReply reply = pinger.Send(ip, 1000, b, new PingOptions(ttl, true));
                if (reply.Address == null)
                {
                    strTrace += "\r\r*******";
                    continue;
                }
                else
                {
                    string hostName;
                    try
                    {
                        hostName = Dns.Resolve(reply.Address.ToString()).HostName;
                    }
                    catch (Exception)
                    {
                        hostName = "";
                    }
                    PingReply roundTripReply = pinger.Send(reply.Address);
                    string x = string.Format("{0}\t\t\t\t\t{1}\t\t\t\t\t\t{2}ms", reply.Address.ToString(), hostName, roundTripReply.RoundtripTime);
                    strTrace += "\r";
                    strTrace += x;
                }
                if (reply.Address.ToString() == ip.ToString())
                    break;
            }
        }
        catch (Exception ex)
        {
 
        }
    }

    private void WriteTracertFile()
    {
        string fileName = "Tracert" + DateTime.Now.ToString().Replace(" ", "").Replace("/", "").Replace(":", "") + ".txt";
        FileStream fs = new FileStream(Server.MapPath(fileName), FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write(strTrace);
        sw.Close();
        fs.Close();
        lblPingTracert.Text += "<a href='" + fileName + "' target='_blank'>" + fileName + DateTime.Now.TimeOfDay + "</a><BR>";
    }
    protected void btnLoad_Click(object sender, EventArgs e)
    {
        byte []content;
        content = FileUpload1.FileBytes;
        Stream strm = Stream.Null;            
        strm.Write(content,0,content.Length);
        StreamReader sr = new StreamReader(FileUpload1.FileContent);
        txtDomaiList.Text = sr.ReadToEnd();
        sr.Close();        
    }





    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindData();
    }
}